package com.glodon.paas.account.security.spring;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.glodon.paas.account.api.bean.AccountConstant;
import com.glodon.paas.account.biz.UserBiz;
import com.glodon.paas.account.dao.domain.UserEntity;
import com.glodon.paas.util.SimpleBeanConverter;


/**
 * @author wangc
 */
@Component("userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Autowired
    private UserBiz userBiz;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOGGER.debug("Loading user by username: {}", username);
        UserEntity dbUser = userBiz.getUserByAccountName(username, null, AccountConstant.USER_STATUS_ACTIVE);
        if (dbUser == null) {
            throw new UsernameNotFoundException(username);
        }
        LOGGER.debug("User id is: {}", dbUser.getId());
        LoginUser userdetail = SimpleBeanConverter.converte(dbUser, LoginUser.class);
        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(userdetail);

        userdetail.setEnabled(true);
        userdetail.setAccountNonExpired(true);
        userdetail.setCredentialsNonExpired(true);
        userdetail.setAccountNonLocked(true);
        userdetail.setAuthorities(grantedAuths);
        userdetail.setPasswordSalt(dbUser.getPasswordSalt());
        return userdetail;
    }

    private Set<GrantedAuthority> obtionGrantedAuthorities(LoginUser user) {
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
//        List<Role> roles = user.getRoles();

//        if (roles == null || roles.size() <= 0) {
            //default role of a user
            authSet.add(new SimpleGrantedAuthority("ROLE_USER"));
//        } else {
//            for (Role role : roles) {
//                List<ResourceAA> tempRes = role.getResources();
//                for (ResourceAA res : tempRes) {
//                    authSet.add(new SimpleGrantedAuthority(res.getName()));
//                }
//            }
//        }
        return authSet;
    }
}
